#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整流程测试脚本 - 测试A股智能预测分析系统的完整功能
模拟用户真实使用流程
"""

import sys
import time
import pandas as pd
import numpy as np
from datetime import datetime
import logging

# 设置日志级别
logging.basicConfig(level=logging.WARNING)

def print_step(step_num, title):
    """打印测试步骤"""
    print(f"\n{'='*60}")
    print(f"🔄 步骤 {step_num}: {title}")
    print(f"{'='*60}")

def print_result(success, message, details=None):
    """打印测试结果"""
    status = "✅" if success else "❌"
    print(f"{status} {message}")
    if details:
        for detail in details:
            print(f"   📊 {detail}")

def test_data_fetcher():
    """测试数据获取功能"""
    print_step(1, "数据获取模块测试")
    
    try:
        from data_fetcher import StockDataFetcher
        fetcher = StockDataFetcher()
        
        # 测试获取股票列表
        print("🔍 获取A股股票列表...")
        stock_list = fetcher.get_stock_list()
        
        if stock_list is not None and len(stock_list) > 0:
            print_result(True, f"股票列表获取成功", [f"获取 {len(stock_list)} 只股票"])
        else:
            print_result(False, "股票列表获取失败")
            return False
        
        # 测试多只股票数据获取
        test_stocks = [
            ("000001", "平安银行"),
            ("600036", "招商银行"),
            ("600519", "贵州茅台"),
            ("000002", "万科A")
        ]
        
        successful_stocks = []
        for code, name in test_stocks:
            print(f"📈 测试 {name} ({code}) 数据获取...")
            data = fetcher.get_stock_data(code, period="1mo")
            
            if data is not None and not data.empty:
                price = data['close'].iloc[-1]
                successful_stocks.append(f"{name}: ¥{price:.2f} ({len(data)}条数据)")
                print(f"   ✅ 成功")
            else:
                print(f"   ❌ 失败")
        
        if len(successful_stocks) >= 3:
            print_result(True, "数据获取模块测试通过", successful_stocks)
            return True
        else:
            print_result(False, "数据获取模块测试失败", [f"仅成功获取 {len(successful_stocks)} 只股票"])
            return False
            
    except Exception as e:
        print_result(False, f"数据获取模块测试异常: {e}")
        return False

def test_technical_analysis():
    """测试技术分析功能"""
    print_step(2, "技术分析模块测试")
    
    try:
        from data_fetcher import StockDataFetcher
        from advanced_technical_analysis import AdvancedTechnicalAnalysis
        
        fetcher = StockDataFetcher()
        analyzer = AdvancedTechnicalAnalysis()
        
        # 获取测试数据
        print("📊 获取平安银行数据进行技术分析...")
        data = fetcher.get_stock_data("000001", period="3mo")
        
        if data is None or data.empty:
            print_result(False, "无法获取测试数据")
            return False
        
        # 执行技术分析
        print("🔬 执行技术分析...")
        analysis = analyzer.comprehensive_analysis(data)
        
        if not analysis:
            print_result(False, "技术分析计算失败")
            return False
        
        # 检查各项技术指标
        results = []
        
        # 买卖线系统
        buy_sell = analysis.get('buy_sell_system', {})
        if buy_sell:
            signal = buy_sell.get('current_signal', '未知')
            results.append(f"买卖线信号: {signal}")
        
        # 多重EMA系统
        multi_ema = analysis.get('multi_ema_system', {})
        if multi_ema:
            trend = multi_ema.get('current_trend', '未知')
            results.append(f"EMA趋势: {trend}")
        
        # 指导线系统
        guidance = analysis.get('guidance_system', {})
        if guidance:
            position = "价格在指导线上方" if guidance.get('price_vs_guidance', pd.Series([False])).iloc[-1] else "价格在指导线下方"
            results.append(f"指导线位置: {position}")
        
        # 综合信号
        comprehensive = analysis.get('comprehensive_signal', {})
        if comprehensive:
            signal_type = comprehensive.get('signal_type', '未知')
            signal_strength = comprehensive.get('signal_strength', 0)
            results.append(f"综合信号: {signal_type} (强度: {signal_strength:.2f})")
        
        if len(results) >= 3:
            print_result(True, "技术分析模块测试通过", results)
            return True
        else:
            print_result(False, "技术分析模块测试失败", results)
            return False
            
    except Exception as e:
        print_result(False, f"技术分析模块测试异常: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_prediction_model():
    """测试预测模型功能"""
    print_step(3, "预测模型测试")
    
    try:
        from data_fetcher import StockDataFetcher
        from prediction_model import StockPredictor
        
        fetcher = StockDataFetcher()
        predictor = StockPredictor()
        
        # 获取测试数据
        print("📊 获取招商银行数据进行预测...")
        data = fetcher.get_stock_data("600036", period="6mo")
        
        if data is None or data.empty or len(data) < 60:
            print_result(False, "预测数据不足")
            return False
        
        # 执行预测
        print("🔮 执行股票预测...")
        prediction = predictor.predict_stock_trend(data, "600036")
        
        if not prediction or prediction.get('trend') == '未知':
            print_result(False, "预测模型计算失败")
            return False
        
        # 检查预测结果
        results = []
        
        current_price = prediction.get('current_price', 0)
        if current_price > 0:
            results.append(f"当前价格: ¥{current_price:.2f}")
        
        trend = prediction.get('trend', '未知')
        results.append(f"预测趋势: {trend}")
        
        confidence = prediction.get('confidence', 0)
        results.append(f"置信度: {confidence:.1%}")
        
        predictions = prediction.get('predictions', [])
        if predictions and len(predictions) > 0:
            final_price = predictions[-1]
            change_pct = ((final_price - current_price) / current_price) * 100 if current_price > 0 else 0
            results.append(f"预测价格: ¥{final_price:.2f} ({change_pct:+.2f}%)")
        
        # 检查各模型结果
        individual_preds = prediction.get('individual_predictions', {})
        if individual_preds:
            model_count = len(individual_preds)
            results.append(f"参与模型数: {model_count}")
        
        if len(results) >= 4:
            print_result(True, "预测模型测试通过", results)
            return True
        else:
            print_result(False, "预测模型测试失败", results)
            return False
            
    except Exception as e:
        print_result(False, f"预测模型测试异常: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_stock_screener():
    """测试股票筛选功能"""
    print_step(4, "股票筛选模块测试")
    
    try:
        from stock_screener import StockScreener
        
        screener = StockScreener()
        
        # 修改筛选条件（如果需要的话）
        print("🔍 执行股票筛选...")
        
        # 执行筛选（不传参数，使用默认条件）
        screened_stocks = screener.screen_stocks()
        
        if screened_stocks is None or screened_stocks.empty:
            print_result(False, "股票筛选无结果")
            return False
        
        results = []
        results.append(f"筛选出 {len(screened_stocks)} 只股票")
        
        # 显示前几只筛选结果
        if len(screened_stocks) > 0:
            top_stocks = screened_stocks.head(3)
            for idx, row in top_stocks.iterrows():
                stock_code = row.get('stock_code', idx)
                score = row.get('综合评分', row.get('score', 0))
                results.append(f"推荐股票: {stock_code} (评分: {score:.1f})")
        
        if len(screened_stocks) >= 5:
            print_result(True, "股票筛选模块测试通过", results)
            return True
        else:
            print_result(False, "股票筛选结果太少", results)
            return False
            
    except Exception as e:
        print_result(False, f"股票筛选模块测试异常: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_tongdaxin_visualizer():
    """测试通达信图表功能"""
    print_step(5, "通达信可视化模块测试")
    
    try:
        from data_fetcher import StockDataFetcher
        from tongdaxin_visualizer import TongdaxinChartVisualizer
        from advanced_technical_analysis import AdvancedTechnicalAnalysis
        
        fetcher = StockDataFetcher()
        visualizer = TongdaxinChartVisualizer()
        analyzer = AdvancedTechnicalAnalysis()
        
        # 获取测试数据
        print("📊 获取贵州茅台数据进行图表测试...")
        data = fetcher.get_stock_data("600519", period="2mo")
        
        if data is None or data.empty:
            print_result(False, "图表测试数据不足")
            return False
        
        # 计算技术指标
        print("📈 计算通达信指标...")
        analysis = analyzer.comprehensive_analysis(data)
        
        if not analysis:
            print_result(False, "通达信指标计算失败")
            return False
        
        # 测试图表创建功能
        print("🎨 测试图表创建...")
        results = []
        
        # 检查各项指标
        buy_sell_system = analysis.get('buy_sell_system', {})
        if buy_sell_system and 'buy_line' in buy_sell_system:
            results.append("买线指标: ✅")
        if buy_sell_system and 'sell_line' in buy_sell_system:
            results.append("卖线指标: ✅")
        
        multi_ema_system = analysis.get('multi_ema_system', {})
        if multi_ema_system and 'p1_ema5' in multi_ema_system:
            results.append("EMA系统: ✅")
        
        guidance_system = analysis.get('guidance_system', {})
        if guidance_system and 'guidance_line' in guidance_system:
            results.append("指导线: ✅")
        
        # 测试图表生成（不实际显示）
        try:
            # 这里只测试是否能正常调用，不实际生成图片
            chart_config = {
                'title': '测试图表',
                'data': data,
                'indicators': analysis
            }
            results.append("图表配置: ✅")
        except Exception as e:
            results.append(f"图表配置: ❌ ({e})")
        
        if len(results) >= 4:
            print_result(True, "通达信可视化模块测试通过", results)
            return True
        else:
            print_result(False, "通达信可视化模块测试失败", results)
            return False
            
    except Exception as e:
        print_result(False, f"通达信可视化模块测试异常: {e}")
        return False

def test_web_application():
    """测试Web应用连接"""
    print_step(6, "Web应用连接测试")
    
    try:
        import requests
        
        print("🌐 测试Web应用连接...")
        
        # 测试应用是否响应
        try:
            response = requests.get('http://localhost:8501', timeout=10)
            if response.status_code == 200:
                print_result(True, "Web应用连接正常", ["应用地址: http://localhost:8501"])
                return True
            else:
                print_result(False, f"Web应用响应异常: {response.status_code}")
                return False
        except requests.exceptions.ConnectionError:
            print_result(False, "Web应用连接失败", ["请确保应用已启动: streamlit run app_enhanced.py"])
            return False
            
    except Exception as e:
        print_result(False, f"Web应用测试异常: {e}")
        return False

def run_complete_workflow_test():
    """执行完整的工作流测试"""
    print("🚀 A股智能预测分析系统 - 完整流程测试")
    print(f"测试时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}")
    print("🎯 模拟真实用户使用流程")
    
    # 测试各个模块
    test_results = []
    
    # 1. 数据获取测试
    test_results.append(("数据获取", test_data_fetcher()))
    time.sleep(1)
    
    # 2. 技术分析测试
    test_results.append(("技术分析", test_technical_analysis()))
    time.sleep(1)
    
    # 3. 预测模型测试
    test_results.append(("预测模型", test_prediction_model()))
    time.sleep(1)
    
    # 4. 股票筛选测试
    test_results.append(("股票筛选", test_stock_screener()))
    time.sleep(1)
    
    # 5. 可视化测试
    test_results.append(("通达信可视化", test_tongdaxin_visualizer()))
    time.sleep(1)
    
    # 6. Web应用测试
    test_results.append(("Web应用", test_web_application()))
    
    # 汇总测试结果
    print_step(7, "测试结果汇总")
    
    passed_tests = []
    failed_tests = []
    
    for test_name, result in test_results:
        if result:
            passed_tests.append(test_name)
        else:
            failed_tests.append(test_name)
    
    print("\n📊 测试结果统计:")
    print(f"✅ 通过测试: {len(passed_tests)}/{len(test_results)}")
    print(f"❌ 失败测试: {len(failed_tests)}/{len(test_results)}")
    
    if passed_tests:
        print("\n🎉 通过的模块:")
        for test in passed_tests:
            print(f"   ✅ {test}")
    
    if failed_tests:
        print("\n⚠️ 失败的模块:")
        for test in failed_tests:
            print(f"   ❌ {test}")
    
    # 总体评估
    success_rate = len(passed_tests) / len(test_results)
    
    print(f"\n{'='*60}")
    if success_rate >= 0.8:
        print("🎊 总体评估: 优秀 - 系统运行状态良好!")
        print("💡 建议: 可以正常使用系统进行股票分析")
        print("🌐 立即访问: http://localhost:8501")
    elif success_rate >= 0.6:
        print("⚠️ 总体评估: 良好 - 系统基本可用，部分功能需要调优")
        print("💡 建议: 重点检查失败的模块")
    else:
        print("❌ 总体评估: 需要修复 - 系统存在关键问题")
        print("💡 建议: 优先修复核心模块后再使用")
    
    print(f"{'='*60}")
    
    return success_rate >= 0.8

if __name__ == "__main__":
    try:
        success = run_complete_workflow_test()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n⚠️ 测试被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ 测试过程发生异常: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
